package com.itheima.rabbitmq;

import com.itheima.domain.dto.VoucherOrderMessageDTO;
import com.itheima.service.IVoucherOrderService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * 秒杀订单消息监听器
 */
@Component
@Slf4j
public class SeckillOrderListener {
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 监听 queue.kun，立即创建订单
     */
    @RabbitListener(queues = "queue.kun")
    public void handleSeckillOrder(VoucherOrderMessageDTO orderMessage,
                                   Channel channel,
                                   Message message) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("========== 处理秒杀订单 ==========");
            log.info("订单ID: {}", orderMessage.getId());
            // 1. 创建订单（扣减库存、保存订单）
            voucherOrderService.createOrder(orderMessage);
            // 2. 发送延时消息：1分钟后检查订单状态
            sendOrderCancelDelayMessage(orderMessage.getId());
            // 3. 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("秒杀订单处理失败: {}", orderMessage, e);
            try {
                channel.basicNack(deliveryTag, false, false);//若没配置死信交换机，则消息会被丢弃
            } catch (Exception ex) {
                log.error("消息拒绝失败", ex);
            }
        }
    }

    /**
     * 发送订单取消延时消息
     * 消息会在延时队列中等待30分钟
     */
    private void sendOrderCancelDelayMessage(Long orderId) {
        try {
            rabbitTemplate.convertAndSend(
                    "order.delay.exchange",  // 延时交换机
                    "order.delay",           // 路由键
                    orderId                  // 消息内容：订单ID
            );
            log.info("延时消息已发送，1分钟后自动检查订单状态");
        } catch (Exception e) {
            log.error("发送延时消息失败", e);
        }
    }
}
